// component/authorize.js
const app = getApp();
//api
// import requestApi from '../../utils/util.js'
Component({

  properties: {
    isShow: Boolean
  },

  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canUseGetUserProfile: false
  },

  lifetimes: {
    attached() {
      if (wx.getUserProfile) {
        this.setData({
          canUseGetUserProfile: true
        })
      }

    }
  },
  methods: {
    // 取消
    cancel() {
      wx.switchTab({
        url: '/pages/index/index',
      })
    },
    gerUserProfile() {
      var that = this;
      wx.getUserProfile({
        lang: 'zh_CN',
        desc: '用于完善用户资料',
        success: (res) => {
          that.sendRequest('', '', '', {
            openId: app.globalData.userInfo.wx_open_id,
            ...res.userInfo
          });
        },
        fail: function (res) {
          console.log(res);
        },
      })
    },
    authHandle() {
      var that = this
      wx.login({
        success(cres) {
          wx.getUserInfo({
            withCredentials: true,
            success: function (res) {
              that.sendRequest(cres.code, res.encryptedData, res.iv);
            },
            fail: function (res) {
              console.log(res);
            },
          });
        }
      });
    },
    sendRequest(code, encryptedData, iv, userInfo) {
      var that = this;
      wx.ajax
        .post("wxGrant.action", {
          code,
          encryptedData,
          iv,
          userInfo: userInfo ? JSON.stringify(userInfo) : '',
        })
        .then((res) => {
          if (res.success) {
            app.globalData.sessionInfo = res.result; //用户sessionkey & openid
            // 本地存储登录用户信息
            wx.setStorageSync("userInfo", res.result);
            that.triggerEvent('success', res.result)
          } else {
            wx.showToast({
              title: res.msg,
              duration: 2000,
              icon: "none",
            });
          }
        });
    }
  }
})